const ci = require('miniprogram-ci');
const fs = require('fs');
const path = require('path');
const chalk = require('chalk');
const { exec } = require('child_process');
const prompts = require('prompts');

const ciParams = fs.readFileSync(path.resolve(__dirname, '../wx-ci-params.json'), 'utf-8');
let paramsJson = JSON.parse(ciParams);
const project = new ci.Project({
  appid: paramsJson.appid,
  type: 'miniProgram',
  projectPath: paramsJson.projectPath,
  privateKeyPath: paramsJson.cikey,
  ignores: ['node_modules/**/*'],
});

function getPackageJson() {
  let packageJson = fs.readFileSync(path.resolve(__dirname, '../package.json'), 'utf-8');
  return JSON.parse(packageJson);
}
function setPackageJsonVersion(version) {
  let packageJson = getPackageJson();
  packageJson.version = version;
  fs.writeFileSync(path.resolve(__dirname, '../package.json'), JSON.stringify(packageJson, null, 2));
}
function newVersion(version) {
  let [a, b, c] = version.split('.').map((x) => +x);

  if (c + 1 >= 99) {
    b++;
    c = 0;
  } else {
    c++;
  }
  if (b + 1 >= 99) {
    a++;
    b = 0;
  }
  return [a, b, c].join('.');
}
//获取全局git用户名
function getGitUser() {
  return new Promise((resolve, reject) => {
    exec('git config --global user.name', (err, stdout, stderr) => {
      if (err) {
        resolve('');
      } else {
        resolve(stdout.trim());
      }
    });
  });
}

//启动上传
async function start() {
  //   const response = await prompts({
  //     type: 'text',
  //     name: 'msg',
  //     message: '请输入版本描述(若没有版本描述则直接回车)',
  //   });
  const response = null;
  let gitUser = await getGitUser();
  const version = newVersion(getPackageJson().version);
  console.log(chalk.green('开始上传体验版...'));
  let message = `版本号：${version}、版本描述：` + (response?.msg || '体验版更新');
  if (gitUser) {
    message = `操作人：${gitUser}、` + message;
  }
  await ci.upload({
    project,
    version,
    desc: message,
    setting: {
      es6: true,
    },
  });
  setPackageJsonVersion(newVersion(version));
  console.log(chalk.green(`上传成功！版本号：${version},上传用户：${gitUser}`));
}
start();
